package com.nx.platform.es.biz.query.agg;

import com.nx.platform.es.biz.query.agg.cache.AggCaches;
import com.nx.platform.es.biz.query.agg.handler.AggRequestHandlerChain;
import com.nx.platform.es.common.utils.CommonUtils;
import com.nx.platform.es.entity.response.TermsAggResult;
import org.elasticsearch.action.search.SearchResponse;

/**
 * @author
 * @since 2016年10月21日
 */
public class AggRequestProcessor {

    private final AggRequestHandlerChain handlerChain;
    private final AggCaches aggCaches;

    public AggRequestProcessor(AggRequestHandlerChain handlerChain, AggCaches aggCaches) {
        this.handlerChain = handlerChain;
        this.aggCaches = aggCaches;
    }

    public TermsAggResult request(AggRequestContext context) throws Exception {
        // 请求预处理
        handlerChain.handle(context);
        String trace = context.getTrace().toString();
        String cacheKey = CommonUtils.toMD5(trace);
        context.setCacheKey(cacheKey);

        // 尝试取缓存
        if (context.getExpireAfterWrite() > 0 && !context.isNocache()) {
            TermsAggResult cached = aggCaches.getCache().get(context.getLogPrefix(), cacheKey);
            if (cached != null) {
                return cached;
            }
        }

        // 取缓存失败时执行ES请求
        SearchResponse response = context.getEsClient().getClient().search(context.getRequest());
        context.setResponse(response);
        TermsAggResult result = AggResponses.create(context, response).toTermsAggResult();

        // 请求结果写入缓存
        if (!context.isNocache()) {
            aggCaches.getCache().put(context.getLogPrefix(), cacheKey, result, context.getExpireAfterWrite());
        }
        return result;
    }

}
